# creating stargazer-like tables with brms models

simple.hyp <- function(mod, hypotheses=NULL){
  s <- summary(mod)
  sf <- s$fixed
  if (is.null(hypotheses)==T)
    hyp <- ifelse(sf[,1] > 0, "> 0", "< 0")
  else
    hyp <- hypotheses
  bf <- hypothesis(mod, paste(rownames(sf), hyp))$hypothesis$Evid.Ratio
  smp <- s$chains * (s$iter - s$warmup)
  bf <- ifelse(bf == Inf, smp, bf)
  return(data.frame(hyp, BF = bf))
}

simple.tab <- function(mod, round.est=3, round.bf=0, ...){
  hyp <- simple.hyp(mod, ...)
  hyp$BF <- round(hyp$BF, round.bf)
  hyp$BF <- ifelse(hyp$hyp == "> 0", paste0(hyp$BF, ":1"), paste0("1:",hyp$BF))
  summ <- round(summary(mod)$fixed[,c(1,3,4)], round.est)
  df <- data.frame(summ, BF=hyp$BF)
  names(df) <- c("Estimate", "l-95% CI", "u-95% CI", "BF")
  return(df)
}

one.col <- function(mod, round.est=2, round.bf=0){
  hyp <- simple.hyp(mod)
  hyp$BF <- round(hyp$BF, round.bf)
  hyp$BF <- ifelse(hyp$hyp == "> 0", paste0(hyp$BF, ":1"), paste0("1:",hyp$BF))
  summ <- round(summary(mod)$fixed[,c(1,3,4)], round.est)
  vars <- rownames(summ)
  summ <- paste0(summ[,1], " [", summ[,2], ",", summ[,3], "] ", hyp$BF)
  df <- data.frame(vars=vars, mod=summ, stringsAsFactors=F)
  return(df)
}

multi.tab <- function(models, round.est=3, round.bf=0, ...){
  if (is.list(models)==F){
    print("Models should be included in a list!")
    return(NA)
  }
  vars <- list()
  mod <- list()
  for (i in 1:length(models)){
    df <- one.col(models[[i]], round.est, round.bf)
    vars[[i]] <- df$vars
    mod[[i]] <- df$mod
  }

  common <- Reduce(intersect, vars)
  all <- unlist(vars)
  different <- all[all %in% common == F]
  #names <- unique(c(common[1], different, common[-1]))
  names <- unique(c(common, different))

  mat <- matrix(rep("", length(names)*length(models)), ncol=length(models))
  df <- data.frame(vars=names, mat, stringsAsFactors=F)
  # for (j in 1:length(models)){
  #   k <- 0
  #   for (i in 1:length(names)){
  #     if (df$vars[[i]] %in% vars[[j]]){
  #       k <- k+1
  #       df[i, j+1] <- mod[[j]][k]
  #     }
  #   }
  # }
  for (j in 1:length(models)){
    for (nam in vars[[j]])
      df[which(nam == df$vars), j+1] <- mod[[j]][which(nam == vars[[j]])]
  }  

  new <- data.frame(matrix("", nrow=3*nrow(df), ncol=(1+ncol(df))), stringsAsFactors=F)
  names(new) <- c("Variable", "Statistics", paste0("(", 1:(ncol(new)-2), ")"))
  stats <- c("Est.", "CI 95", "BF")

  ni <- 0
  for (i in 1:nrow(df)){
    ni <- ni + 1
    new[3*(ni-1)+1,1] <- df[ni, 1]
    new[(3*(ni-1)+1):(3*(ni-1)+3), 2] <- stats
    for (j in 2:ncol(df)){
      if(df[i,j] != "")
        tmp <- unlist(strsplit(df[i,j], " ", fixed=T))
      else
        tmp <- rep("", 3)
      for (k in 1:3)
        new[3*(ni-1)+k, j+1] <- tmp[k]
    }
  }
  return(new)
}

